/*
* @Author: slp
* @Date:   2018-07-05 16:26:25
* @Last Modified by:   ystlong
* @Last Modified time: 2018-07-21 02:53:45
*/

#include <sys/stat.h>
#include "uart.h"


#pragma GCC push_options
#pragma GCC optimize ("O0")


////////////////////////////////////////////////
// patch newlib memset,memcpy not align error //
////////////////////////////////////////////////
void *memset(void *s, int c, size_t n)
{
	char *cs = (char *)s;
	for(int i=0; i<n; i++)
		*cs++ = (char)c;
	return s;
}

void *memcpy(void *dest, const void *src, size_t n)
{
	char *d = (char *)dest;
	char *s = (char *)src;
	for(int i=0; i<n; i++)
		*d++ = *s++;
	return dest;
}

///////////////////////////////
// for newlib stall function //
///////////////////////////////
void __real_exit() __attribute__((noreturn));
void _exit(int status)
{
	__real_exit();
}

caddr_t _sbrk(int incr) 
{
	static char *heap_end = NULL;
	extern char heap_low; /* defined by the linker*/
	extern char heap_top; /* defined by the linker */
	char *prev_heap_end;
	if (heap_end == 0) {
		heap_end = &heap_low;
	}
	prev_heap_end = heap_end;
	if (heap_end+incr > &heap_top) {
		return (caddr_t)0;
	}
	heap_end += incr;
	return (caddr_t) prev_heap_end;
}

int _close(int file) 
{ 
	return -1;
}

int _fstat(int file, struct stat *st)
{
	st->st_mode = S_IFCHR;
	return 0;
}

int _isatty(int file) 
{
	return 1;
}

int _lseek(int file, int ptr, int dir)
{
	return 0;
}

int _read(int file, char *ptr, int len)
{
	int todo;
	if(len == 0) return 0;
	for(todo = 1; todo<len; todo++){
		*ptr++ = uart_getc();
	}
}

int _write(int file, char *ptr, int len) 
{
	int todo;
	for(todo = 0; todo < len; todo++)
		uart_putc(*ptr++);
	return len;
}

void initialise_monitor_handles()
{

}

#pragma GCC pop_options
